<?php

namespace App\Admin\Controllers;

use App\Models\Administrator;
use App\Models\Team;
use App\Models\User;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;

class UsersController extends Controller
{
    use ModelForm;

    private $header = '用户管理';
    private $description = '用户管理';
    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description($this->description);

            $content->body($this->grid());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(User::class, function (Grid $grid) {
            $grid->disableCreateButton();
            $grid->disableRowSelector();
            $grid->disableActions();
            if (Admin::user()->type === Administrator::TEAM_LEADER) {
                $grid->model()->where('team_id', Admin::user()->team_id);
            }
            $grid->team()->name('团体');
            $grid->name('姓名');
            $grid->phone_number('电话');
            $grid->open_id('唯一识别码');
            $grid->created_at('注册时间');

            $grid->filter(function($filter){
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
            });
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableEdit();
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($user = null)
    {
        return Admin::form(User::class, function (Form $form) use($user) {

            $form->text('name', '姓名')->rules('required');
            $form->text('phone_number', '手机号')->rules('required');
            $form->password('password', '密码')->rules('required');
            $form->display('open_id', 'open_id');

            $teams = Team::query()->pluck('name', 'id');
            $form->select('team_id', '团体')->options($teams)->rules('required');
            $form->image('avatar', '头像')->rules('required');
        });
    }
}
